﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using workflowMVC.Models;
using DataTool;
using DataTables;

namespace workflowMVC.Controllers
{
    [Authorize(Roles="Admin")]
    public class AdminController : Controller
    {
        //
        // GET: /Admin/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CreateAccount()
        {
            ViewBag.Description = "Tạo tài khoản";
            List<SelectListItem> roles = new List<SelectListItem>();
            foreach (var r in Util.entity.aspnet_Roles.Where(x => x.RoleName != "Student" && x.RoleName != "Judge"))
            {
                roles.Add(new SelectListItem
                {
                    Value = r.RoleName,
                    Text = r.RoleName,
                });
            }
            ViewBag.rolez = new SelectList(roles, "Value", "Text");
            return View();
        }        

        [HttpPost]
        public ActionResult CreateAccount(AccountModel model)
        {
            if (ModelState.IsValid)
            {
                model.UserName = model.UserName.ToLower();
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, "123456", model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    if(!String.IsNullOrEmpty(model.role))
                        Roles.AddUserToRole(model.UserName, model.role);
                    if(model.IsJudge)
                        Roles.AddUserToRole(model.UserName, "Judge");
                    STAFF s = new STAFF();
                    s.UserName = model.UserName;
                    s.RealName = model.FullName;
                    Util.entity.STAFFs.AddObject(s);
                    Util.entity.SaveChanges();
                    ViewBag.NotifyResult = "Tạo thành khoảnh thành công";
                    return View("NotifyResult");
                }
                else
                {
                    ModelState.AddModelError("", Util.ErrorCodeToString(createStatus));
                }
            }
            ViewBag.Description = "Tạo tài khoản";
            // If we got this far, something failed, redisplay form
            List<SelectListItem> roles = new List<SelectListItem>();
            foreach (var r in Util.entity.aspnet_Roles.Where(x => x.RoleName != "Student" && x.RoleName != "Judge"))
            {
                
                roles.Add(new SelectListItem
                {
                    Value = r.RoleName,
                    Text = r.RoleName,
                });
            }
            ViewBag.rolez = new SelectList(roles, "Value", "Text");
            return View(model);
        }

        

        public ActionResult EditAccount(string id)
        {
            ViewBag.Description = "Sửa tài khoản";
            wfdbEntities db = new wfdbEntities();
            var acc = db.STAFFs.Where(x => x.UserName == id).FirstOrDefault();
            if(acc == null)
                return View("Error");
            AccountModel m = new AccountModel
            {
                FullName = acc.RealName,
                UserName = acc.UserName,
                role = Roles.GetRolesForUser(acc.UserName).Except(new string[]{"Judge"}).SingleOrDefault(),
                Email = Membership.GetUser(id).Email,
                IsJudge = Roles.GetRolesForUser(acc.UserName).Contains("Judge")
            };
            List<SelectListItem> roles = new List<SelectListItem>();
            foreach (var r in Util.entity.aspnet_Roles.Where(x => x.RoleName != "Student" && x.RoleName != "Judge"))
            {
                
                roles.Add(new SelectListItem
                {
                    Value = r.RoleName,
                    Text = r.RoleName,
                });
            }
            ViewBag.rolez = new SelectList(roles, "Value", "Text");
            return View("CreateAccount",m);
        }

        [HttpPost]
        public ActionResult EditAccount(AccountModel m)
        {
            if (ModelState.IsValid)
            {
                wfdbEntities db = new wfdbEntities();
                var acc = db.STAFFs.Where(x => x.UserName == m.UserName).FirstOrDefault();
                acc.RealName = m.FullName;
                if (Roles.GetRolesForUser(acc.UserName).Length !=0)
                    Roles.RemoveUserFromRoles(acc.UserName, Roles.GetRolesForUser(acc.UserName));
                if (!String.IsNullOrEmpty(m.role))
                    Roles.AddUserToRole(m.UserName, m.role);
                if (m.IsJudge)
                    Roles.AddUserToRole(m.UserName, "Judge");
                var user = Membership.GetUser(acc.UserName);
                user.Email = m.Email;
                Membership.UpdateUser(user);
                ViewBag.Notifyresult = "Sửa thông tin thành công";
                db.SaveChanges();
                return View("Notifyresult");
            }
            ViewBag.Description = "Sửa tài khoản";
            List<SelectListItem> roles = new List<SelectListItem>();
            foreach (var r in Util.entity.aspnet_Roles.Where(x => x.RoleName != "Student" && x.RoleName != "Judge"))
            {

                roles.Add(new SelectListItem
                {
                    Value = r.RoleName,
                    Text = r.RoleName,
                });
            }
            ViewBag.rolez = new SelectList(roles, "Value", "Text");
            return View("CreateAccount", m);
        }

        public ActionResult JudgeAssignList()
        {
            ViewBag.datasource = Url.Action("JudgeAssignData");
            return View();
        }

        public void DismissJudge(string username)
        {
            Roles.RemoveUserFromRole(username,"Judge");
        }

        public void AssignJudge(string username)
        {
            Roles.AddUserToRole(username, "Judge");
        }

        public ActionResult JudgeAssignData()
        {
            wfdbEntities db = new wfdbEntities();

            var data = db.STAFFs.AsEnumerable().Select(x =>
                new ListAccountModel
                {
                    Roles = db.aspnet_Users.SingleOrDefault(z => z.UserName == x.UserName).aspnet_Roles.Select(z => z.RoleName).Except(new string[] {"Judge"}).FirstOrDefault(),
                    RealName = x.RealName,
                    UserName = x.UserName,
                    Action = ""
                }
                );
            var data2 = db.STUDENTs.AsEnumerable().Select(x =>
                new ListAccountModel
                {
                    Roles = db.aspnet_Users.SingleOrDefault(z => z.UserName == x.NumCode).aspnet_Roles.Select(z => z.RoleName).Except(new string[] { "Judge" }).FirstOrDefault(),
                    RealName = x.Name,
                    UserName = x.NumCode,
                    Action = ""
                }
                );
            data = data.Concat(data2);
            var cs = new DataTableParser<ListAccountModel>(Request, data.AsQueryable()).Parse();
            cs.aaData.ForEach(x =>
            {
                string checkedz = "";
                if (Roles.GetRolesForUser(x[1]).Contains("Judge"))
                    checkedz = "checked";
                x[3] = "<input type='checkbox' value='" + x[1] + @"' " + checkedz + "/>";
            }

                );
            return Json(cs);
        }

        public ActionResult ListAccount()
        {
            ViewBag.datasource = Url.Action("ListAccountData");
            return View();
        }

        public JsonResult ListAccountData()
        {
            wfdbEntities db = new wfdbEntities();

            var data = db.STAFFs.AsEnumerable().Select(x =>
                new ListAccountModel
                {
                    Roles = db.aspnet_Users.SingleOrDefault(z => z.UserName == x.UserName).aspnet_Roles.Select(z => z.RoleName).DefaultIfEmpty().Aggregate((res, item) => res += "<br/> " + item),
                    RealName = x.RealName,
                    UserName = x.UserName,
                    Action = ""
                }
                );
            var cs = new DataTableParser<ListAccountModel>(Request, data.AsQueryable()).Parse();
            cs.aaData.ForEach(x =>
            {
                x[3] = Util.getsTableLink
            (new { @class = Util.edit },
            new { title = "Sửa", href = Url.Action("EditAccount",new {id= x[1]}) });
            }

                );
            return Json(cs);
        }
    }
}
